package com.kkd.kkdapp.activity;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.android_async_http.AsyncHttpResponseHandler;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.manager.HttpCallBack;

import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;

import com.umeng.message.entity.UMessage;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.sax.TextElementListener;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class NoticeDetailActivity extends BaseActivity implements
		OnClickListener {

	private RelativeLayout vertical_top_img; // 返回键
	private TextView title;
	private TextView time;
	private TextView content;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vertical_information);
		initView();

	}

	@Override
	protected void onResume() {
		super.onResume();
		getMessage();
	}

	public void initView() {
		vertical_top_img = (RelativeLayout) this
				.findViewById(R.id.vertical_top_img);
		title = (TextView) this.findViewById(R.id.title);
		time = (TextView) this.findViewById(R.id.time);
		content = (TextView) this.findViewById(R.id.content);

		vertical_top_img.setOnClickListener(this);
	}

	public void getMessage() {
		Intent intent = this.getIntent();
		String id = intent.getStringExtra("id");
		String titleName = intent.getStringExtra("tilte");
		String desc = intent.getStringExtra("desc");
		if (!TextUtils.isEmpty(titleName) && !TextUtils.isEmpty(desc)) {

			title.setText(titleName);
			content.setText(desc);

		} else {
			if (!TextUtils.isEmpty(id)) {
				queryOnePersonMsg(id);
			} else {// 说明是新加的逻辑，判断是否是将信息已经传过来了
				String json = intent.getStringExtra("msg");
				if (!TextUtils.isEmpty(json)) {
					Gson gson = new Gson();
					UMessage msg = gson.fromJson(json, UMessage.class);
					String msg_id = "";
					try {
						msg_id = msg.extra.get("message_id").toString();
					} catch (Exception e) {
						// TODO: handle exception
					}
					String customerIdAndToken = PreferenceUtils.getInstance()
							.getcustomerId(this);
					String[] cat = customerIdAndToken.split("&");
					if (!TextUtils.isEmpty(msg_id) && cat != null
							&& cat.length > 1) {
						queryOnePersonMsg(msg_id);
					} else {
						if (!TextUtils.isEmpty(msg.title)) {
							title.setText(msg.title);
						}
						SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
						time.setText(sf.format(new Date()));
						if (!TextUtils.isEmpty(msg.text)) {
							content.setText(msg.text);
						}
					}

				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.vertical_top_img:
			finish();
			break;
		}

	}

	public void queryOnePersonMsg(String id) {
		KkdHttpMagager.getInstance().getVerticalInformationManager(id,
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							LogUtil.e("responseString", responseString);
							JSONObject data = new JSONObject(responseString);
							if (data.getString("title") != null
									|| !"".equals(data.getString("title"))) {
								title.setText(data.getString("title"));
							}

							if (data.getString("publishDate") != null
									|| !"".equals(data.getString("publishDate"))) {
								time.setText(data.getString("publishDate"));
							}

							if (data.getString("description") != null
									|| !"".equals(data.getString("description"))) {
								content.setText(data.getString("description"));
								interceptHyperLink(content);
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(desc);
					}
				});
	}

	/**
	 * 拦截超链接
	 * 
	 * @param tv
	 */
	private void interceptHyperLink(TextView tv) {
		tv.setMovementMethod(LinkMovementMethod.getInstance());
		CharSequence text = tv.getText();
		if (text instanceof Spannable) {
			int end = text.length();
			Spannable spannable = (Spannable) tv.getText();
			URLSpan[] urlSpans = spannable.getSpans(0, end, URLSpan.class);
			if (urlSpans.length == 0) {
				return;
			}

			SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
					text);
			// 循环遍历并拦截 所有http://开头的链接
			for (URLSpan uri : urlSpans) {
				String url = uri.getURL();
				if (url.indexOf("http://") == 0) {
					CustomUrlSpan customUrlSpan = new CustomUrlSpan(this, url);
					spannableStringBuilder.setSpan(customUrlSpan,
							spannable.getSpanStart(uri),
							spannable.getSpanEnd(uri),
							Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
				} else if (url.indexOf("https://") == 0) {
					CustomUrlSpan customUrlSpan = new CustomUrlSpan(this, url);
					spannableStringBuilder.setSpan(customUrlSpan,
							spannable.getSpanStart(uri),
							spannable.getSpanEnd(uri),
							Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
				}
			}
			tv.setText(spannableStringBuilder);
		}
	}

	public class CustomUrlSpan extends ClickableSpan {

		private Context context;
		private String url;

		public CustomUrlSpan(Context context, String url) {
			this.context = context;
			this.url = url;
		}

		@Override
		public void onClick(View widget) {
			// 在这里可以做任何自己想要的处理
			Intent intent = new Intent(context, KKDWebActivity.class);
			intent.putExtra("url", url);
			context.startActivity(intent);
		}
	}
}
